<template>
  <div class="user-main">
    <div style="display: flex;flex-direction: row;justify-content: flex-start">
      <img src="/logoc.png" class="app-loading-logo" alt="Logo" style="width:80px;height:26px;"/>
      <span style="color:#006cb4;text-align:center;font-size:14px;line-height: 26px;letter-spacing: 0.5px;">数据中心运行环境实时监测系统<span style="font-weight: bold;">--移动巡检</span></span>
    </div>
    <a-form
      class="user-layout-login"
      ref="formRef"
      :model="formData"
      @submit="handleLogin"
    >
      <a-tabs
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
      >
        <a-tab-pane key="tab1" tab="账号登录">
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="请输入帐户名"
              v-model:value="formData.account"
            >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>

          <a-form-item>
            <a-input-password
              size="large"
              placeholder="请输入密码"
              v-model:value="formData.password"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input-password>
          </a-form-item>

          <a-form-model-item prop="inputCode">
            <a-input v-model:value="formData.inputCode" size="large" type="text" placeholder="请输入验证码">
              <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              <template #suffix>
                <img
                  v-if="randCodeData.requestCodeSuccess"
                  style="margin-top: 2px; max-width: initial"
                  :src="randCodeData.randCodeImage"
                  @click="handleChangeCheckCode"
                />
                <img v-else style="margin-top: 2px;" src="../../../assets/images/checkcode.png"
                     @click="handleChangeCheckCode"/>
              </template>
            </a-input>
          </a-form-model-item>
        </a-tab-pane>
      </a-tabs>

      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="loading"
        >登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref, toRaw, unref, computed, onMounted} from 'vue';

import {Checkbox, Form, Input, Row, Col, Button, Divider} from 'ant-design-vue';
import {GithubFilled, WechatFilled, DingtalkCircleFilled, createFromIconfontCN} from '@ant-design/icons-vue';
import {useI18n} from '/@/hooks/web/useI18n';
import {useMessage} from '/@/hooks/web/useMessage';

import {useUserStore} from '/@/store/modules/user';
import {LoginStateEnum, useLoginState, useFormRules, useFormValid} from './useLogin';
import {useDesign} from '/@/hooks/web/useDesign';
import {getCodeInfo} from '/@/api/sys/user';
//import { onKeyStroke } from '@vueuse/core';

const ACol = Col;
const ARow = Row;
const FormItem = Form.Item;
const InputPassword = Input.Password;

const {t} = useI18n();
const {notification, createErrorModal} = useMessage();
const {prefixCls} = useDesign('login');
const userStore = useUserStore();

const {setLoginState, getLoginState} = useLoginState();
const {getFormRules} = useFormRules();

const formRef = ref();
const loading = ref(false);
const rememberMe = ref(false);

const formData = reactive({
  account: 'admin',
  password: '123456',
  inputCode: '',
});
const randCodeData = reactive({
  randCodeImage: '',
  requestCodeSuccess: false,
  checkKey: null,
});

const {validForm} = useFormValid(formRef);

//onKeyStroke('Enter', handleLogin);

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

async function handleLogin() {
  const data = {account: formData.account, password: formData.password, inputCode: formData.inputCode};
  console.log(data);
  if (!data) return;
  try {
    loading.value = true;
    const {userInfo} = await userStore.login(
      toRaw({
        password: data.password,
        username: data.account,
        captcha: data.inputCode,
        checkKey: randCodeData.checkKey,
        mode: 'none', //不要默认的错误提示
      }),
      '/xj'
    );
    if (userInfo) {
      notification.success({
        message: t('sys.login.loginSuccessTitle'),
        description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realname}`,
        duration: 3,
      });
    }
  } catch (error) {
    notification.error({
      message: t('sys.api.errorTip'),
      description: error.message || t('sys.api.networkExceptionMsg'),
      duration: 3,
    });
    loading.value = false;

    //update-begin-author:taoyan date:2022-5-3 for: issues/41 登录页面，当输入验证码错误时，验证码图片要刷新一下，而不是保持旧的验证码图片不变
    handleChangeCheckCode();
    //update-end-author:taoyan date:2022-5-3 for: issues/41 登录页面，当输入验证码错误时，验证码图片要刷新一下，而不是保持旧的验证码图片不变
  }
}

function handleChangeCheckCode() {
  formData.inputCode = '';
  //TODO 兼容mock和接口，暂时这样处理
  randCodeData.checkKey = 1629428467008; //new Date().getTime();
  getCodeInfo(randCodeData.checkKey).then((res) => {
    randCodeData.randCodeImage = res;
    randCodeData.requestCodeSuccess = true;
  });
}

//初始化验证码
onMounted(() => {
  handleChangeCheckCode();
});
</script>


<style lang="less" scoped>

.user-main {
  padding: 40px 20px;
}

.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
